import pinia from './store'
import useUserStore from "./store/modules/user";
import router from "./router";
import nprogress from "nprogress";
import "nprogress/nprogress.css";
nprogress.configure({ showSpinner: false });

const userStore = useUserStore(pinia);
router.beforeEach(async (to, from, next) => {
    document.title = '硅谷甄选 - ' + to.meta?.title;
    nprogress.start();

    console.log(router.getRoutes());
    console.log(to);
    //用到持久化的话 const userStore = useUserStore(pinia); 需要放到这才能生效，但动态路由就失效了
    const token = userStore.token;
    const username = userStore?.userInfo?.name;
    if (token) {
        if (to.path === "/login") next({ path: "/" });
        else {
            if (username) next();
            else {
                try {
                    await userStore.getUserInfo();
                    next({...to, replace: true });
                } catch (e) {
                    await userStore.exitLogin();
                    next({ path: "/login", query: { redirect: to.path } });
                }
            }
        }
    } else {
        if (to.path !== "/login") next({ path: "/login", query: { redirect: to.path } });
        else next();
    }
});

router.afterEach(() => {
    nprogress.done();
});